package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;

import entity.Adress;
import services.AddressService;
import services.impl.AddressServiceImpl;

/**
 * Servlet implementation class AdressServlet
 */
@WebServlet("/adress")
public class AdressServlet extends HttpServlet {
	Gson gson = new Gson();
	
	
	AddressService adservice=new AddressServiceImpl(); 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		String adress = request.getParameter("adress");
		
		
		int user_id = (int) session.getAttribute("uid");//获取用户id
		PrintWriter out = response.getWriter();
		List<Adress> adressList = null;
		adressList=adservice.getuserAllAdress(user_id);
		String adre = gson.toJson(adressList);
		System.out.println("adre"+adre);
		
		
		//删除地址
		String temp=request.getParameter("adre_id");
		System.out.println("temp"+temp);
		if(temp!=null) {
			int adre_id=Integer.parseInt(temp);
			
			System.out.println("adre_id"+adre_id);
			int re=adservice.dealuserAdress(adre_id);
			
			
	         if(re > 0) {
	        	 request.getRequestDispatcher("adress.jsp").forward(request, response);
				System.out.println("地址删除成功");
				
			}else {
				System.out.println("地址删除失败");
			}
			
			
		}
	
		
		
		
		//新增地址
		
		if(adress!=null) {
		System.out.println("adress "+adress);
		int res=adservice.InsertIntoAddress(user_id, adress);
		if(res > 0) {
			
			request.getRequestDispatcher("adress.jsp").forward(request, response);
			System.out.println("地址添加成功");
			
		}else {
			System.out.println("地址添加失败");
		}
		}
		out.print(adre);
		out.flush();
		out.close();
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
